"""
This provides the main system for the Web Service.
"""

from multiprocessing import Process, Pool, Manager, Queue
import cherrypy
import json
from Authentication import AuthController, require, member_of, name_is
from tables import tablesDatabase
from MainTable import MainTable
from JsonParse import JSONParser
from Queue import Empty
from background import BackgroundTaskQueue


class RestrictedArea:
    
    # all methods in this controller (and subcontrollers) is
    # open only to members of the admin group
    
    _cp_config = {
        'auth.require': [member_of('admin')]
    }
    
    @cherrypy.expose
    def index(self):
        return """This is the admin only area."""

class JiraReportingSite:


    _cp_config = {
        'tools.sessions.on': True,
        'tools.auth.on': True
    }
    auth = AuthController()
    restricted = RestrictedArea()

    def __init__(self, bgtask):
        self.bgtask = bgtask
        #self.MainDatabase = MainTable("../../databases/main/main.db")
        self.SESSION_KEY = '_cp_username'
   
    """
    @cherrypy.expose
    def loginCheck(self):
        if self.MainDatabase.checkUser(cherrypy.session[self.SESSION_KEY]) == False:
            self.MainDatabase.insertUser(cherrypy.session[self.SESSION_KEY])
            self.MainDatabase.createDashboard("Dashboard", cherrypy.session[self.SESSION_KEY])
        raise cherrypy.HTTPRedirect("/")
    """
    @cherrypy.expose
    def groups(self):
        groups = open("../../dojo/groups.html", "r")
        return groups.read()

    @cherrypy.expose
    def findUsers(self):
        findUsers = open("../../dojo/find_user.html", "r")
        return findUsers.read()

    
    @cherrypy.expose
    @require()
    def index(self):
        dashboard = open("../../dojo/dashboard.html", "r")
        return dashboard.read()

    @cherrypy.expose
    def createUser(self):
        createUser = open("../../dojo/createuser.html", "r")
        return createUser.read()

    @cherrypy.expose
    def getIssues(self, JQL, number):
        print JQL
        print number
        if number == "1":
            jira.getIssue(JQL, username, password)
        elif number == "*":
            jira.getIssues(JQL, username, password)

    @cherrypy.expose
    def operationsList(self):
        db = cherrypy.request.db
        operations = self.MainDatabase.getOperations(cherrypy.session[self.SESSION_KEY])
        return json.dumps(operations)

    @cherrypy.expose
    def importIssues(self):
        test4 = open("../../dojo/import.html", "r")
        return test4.read()

    @cherrypy.expose
    def workIssues(self):
        working_data = open("../../dojo/working_data.html", "r");
        return working_data.read();

    @cherrypy.expose
    def operations(self, opType, value):
        if opType == "runSQL":
            database = tablesDatabase(self.MainDatabase.getLocation(cherrypy.session[self.SESSION_KEY]))
            return database.runSQL(value['table'], value['code'])
        elif opType == "saveSQL" or opType == "savePython":
            self.MainDatabase.addOperation(value['name'], value["opType"], value['operation'], cherrypy.session[self.SESSION_KEY])
            return "Successful"
        elif opType == "runPython":
            return

    """
    @cherrypy.expose
    def getJS(self, item):
        fp = ""
        if item == "createMenu":
            fp = open("../../dojo/createMenu.js", "r")
        elif item == "createTablesList":
            fp = open("../../dojo/createTablesList.js", "r")
        return fp.read()
    """
            
    @cherrypy.expose
    def allBatting(self, data):
        #print data
        data = json.loads(data)
        columns = []
        dataPaths = []
        for search in data['search']:
            columns.append([search[0], search[1].split(",")])
            dataPaths.append(search[1].split(","))
        print dataPaths
        print columns
        #print data
        fp = open("../../json/jira.json", "r")
        self.parser = JSONParser(fp.read())
        fp.close()
        #fp = open("../../json/jira.json", "r")
        #self.data = json.loads(fp.read())
        paths = self.parser.convertPaths(dataPaths)
        print paths
        dataGrid = self.parser.getTable(columns, paths)
        print dataGrid
        #table = self.parser.getItems(["changelog", "histories", 0, ["author", "displayName"], ["items", 0, "field"]], self.data)
        #dataGrid = self.parser.getDataGridStore(["displayName", "field"], table)
        return json.dumps(dataGrid)
    
    @cherrypy.expose
    def attributes(self):
        fp = open("../../json/jira.json", "r")
        self.parser = JSONParser(fp.read())
        attributes = self.parser.getColumns()
        return json.dumps(attributes)

    @cherrypy.expose
    def widget(self):
        create_widget = open("../../dojo/create_widget.html", "r")
        return create_widget.read()

    @cherrypy.expose
    def getJson(self):
        json = open("../../json/jira.json", "r")
        return json.read()

    @cherrypy.expose
    def tree(self):
        tree = open("../../examples/tree.html", "r")
        return tree.read()

    @cherrypy.expose
    @require()
    def dashboard(self, data):
        var = json.loads(data)
        value = var['value']
        if var['type'] == 'Dashboard':
            dashboards = self.MainDatabase.getDashboards(cherrypy.session.get(self.SESSION_KEY, None))
            return json.dumps(dashboards)
        elif var['type'] == 'Widget':
            widgets = self.MainDatabase.getWidgets(value['title'], cherrypy.session.get(self.SESSION_KEY, None), value['location'])
            return json.dumps(widgets)

    @cherrypy.expose
    def data(self, data):
        var = json.loads(data)
        print var
        if var['table'] == 'Test':
            return json.dumps("None")
        elif var['table'] == 'Area':
            series = {"Series A": [1, 2, 0.5, 1.5, 1, 2.8, 0.4], "Series B": [2.6, 1.8, 2, 1, 1.4, 0.7, 2], "Series C": [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2]}
            return json.dumps(series)
        elif var['table'] == 'Pie':
            series = {"Monthly Sales - 2010": [10000,9200,11811,12000,7662,13887,14200,12222,12000,10009,11288,12099]}
            return json.dumps(series)

    @cherrypy.expose
    def table(self, data):
        fp = open("../../json/jira.json", "r")
        self.parser = JSONParser(fp.read())
        fp = open("../../json/jira.json", "r")
        jsonData = json.loads(fp.read())
        columns = [["displayName", "TEXT"], ["field", "TEXT"]]
        database = tablesDatabase("../../databases/tests/u346156.db")
        tablesData = self.parser.getItems(["changelog", "histories", 0, ["author", "displayName"], ["items", 0, "field"]], jsonData)
        database.importTable("test", columns, tablesData)
        print database.getTable("test")
        var = json.loads(data)
        print var
        if var['type'] == 'tableCol':
            value = var['value']
            columns = database.getTableColumns(value['table'], value['typeof'])
            database.destroyTable("test")
            database.close()
            return json.dumps(columns)
        if var['type'] == 'database':
            tables = database.getDatabase()
            database.destroyTable("test")
            database.close()
            return json.dumps(tables)
        database.destroyTable("test")
        database.close()
        return

def workerDatabase(queue):
    while 1:
        try:
            func, args, kwargs = queue.get(block=True, timeout=2)
        except Empty:
            continue
        else:
            tablesDatabase()
            

def workerPool(queue):
    print "Pool Created"
    pool = Pool(4)
    while 1:
        try:
            func, args, kwargs = queue.get(block=True, timeout=2)
        except Empty:
            continue 
        else:
            pool.apply_async(func, args)


import os.path
tutconf = os.path.join(os.path.dirname(__file__), '../../config/tutorial.conf')

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to HelloWorld().index().
    # Register the SQLALchemy plugin
    functionQueue = Queue()
    #databaseQueue = Queue()
    bgtask = BackgroundTaskQueue(cherrypy.engine, functionQueue)
    bgtask.subscribe()
    cherrypy.config.update({'server.socket_host': '127.0.0.1'})
    pool = Process(target=workerPool, args=(functionQueue,))
    pool.start()
    #database = Process(target=workerDatabase, args=(databaseQueue,))
    #database.start()
    from saplugin import SAEnginePlugin
    SAEnginePlugin(cherrypy.engine, 'sqlite:///../../databases/main.db').subscribe()

    # Register the SQLAlchemy tool
    from satool import SATool
    cherrypy.tools.db = SATool()

<<<<<<< HEAD
    cherrypy.quickstart(JiraReportingSite(), '', tutconf)
=======
    cherrypy.quickstart(JiraReportingSite(bgtask), '', {'/': {'tools.db.on': True}})
    #pool.start()
    pool.join()
    #database.join()
>>>>>>> 914d19b8da156bebef165ad546803d63f20b2850
else:
    # This branch is for the test suite; you can ignore it.
    cherrypy.tree.mount(JiraReportingSite(), config=tutconf)
